import edge_tts
import asyncio
import random
import os,shutil
#from pydub import AudioSegment
# edge-tts --list-voices 查看可用的语音列表，然后通过 --voice 选项来选择你想要的声音。
# 通过 --rate 和 --volume 选项来调整语速和音量，-50% 代表降低语速/音量
'''
mp3合并静音文件的方案
https://blog.csdn.net/weixin_55674264/article/details/129334800
'''
BOOK=".\\source\\NewBook1.txt"
BOOK=".\\source\\English3上.txt"
LESSON_RANDOM=1  #全局随机打乱
WORD_WAIT_SECONDS=10
LESSONS=[21,22]
LESSONS=[9,10]
REPEAT_TIMES=2


start_text="亲爱的xxx同学,下面开始听写英语单词,第%s课单词,单词顺序%s,每个单词重复%s次，\
            间隔时间%s秒钟，听写一共{0}个单词，预计用时{1}分{2}秒,请做好准备"%(LESSONS,['不随机','随机打乱'][LESSON_RANDOM],REPEAT_TIMES,WORD_WAIT_SECONDS)
end_text="单词听写全部结束，请xxx同学认真检查听写结果"

voice = 'zh-CN-YunxiNeural' #叙事男
#voice = 'zh-CN-XiaoyiNeural' #微软小伊
voice = 'zh-CN-YunxiaNeural' #儿童女2
#voice = 'zh-CN-YunyangNeural' #播音男
#voice = 'zh-CN-liaoning-XiaobeiNeural' #东北女
#voice = 'zh-CN-shaanxi-XiaoniNeural' #陕西女
rate = '-17%'
volume = '+10%'
TEXT_LIST = []
temp_folder="temp"
output_folder="output"

def check_folders():
    if os.path.exists(temp_folder):
        shutil.rmtree(temp_folder)
    os.makedirs(temp_folder)
    
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
        
def read_words():
    global TEXT_LIST,start_text,end_text
    lesson=0
    word_list=[]
    with open(BOOK, 'rb') as f:
        for line in f:            
            line = line.strip().decode('utf-8')
            if not line or len(line)<1:
                continue
            if line.startswith("Lesson"):
                lesson=int(line.replace("Lesson",""))
                #print("lesson:",lesson)
                continue
            if lesson not in LESSONS:
                continue       
            word_list.append(line)
            
    if LESSON_RANDOM==1:
        random.shuffle(word_list)
    word_list_len= len(word_list)+1
    elapsed = 2 * word_list_len * REPEAT_TIMES + WORD_WAIT_SECONDS * word_list_len
    start_text=start_text.format(len(word_list), int(elapsed/60),elapsed%60)

    TEXT_LIST=[start_text]
    TEXT_LIST = TEXT_LIST + word_list
    TEXT_LIST.append(end_text)
    #print(TEXT_LIST)


async def my_function():
    for idx, txt in enumerate(TEXT_LIST):
        print(idx,txt)
        tts = edge_tts.Communicate(text=txt, voice=voice, rate=rate, volume=volume)
        await tts.save("%s\%s.mp3" % (temp_folder,idx))
    
   
    
def combine_files():
    fname = os.path.basename(BOOK)
    output=".\\%s\\%s-%s.mp4"%(output_folder,fname,LESSONS)  #生成mp4文件,是因为生成的mp3文件，在微信里无法直接播放
    print("combining output file=",output)
    if os.path.exists(output):
        # 如果文件存在，则删除该文件
        os.remove(output)
    mute_file=None
    with open(".\\source\\1second.mp3", 'rb') as fi:
        mute_file = fi.read()
    with open(output, 'wb') as fo:
        for i in range(len(TEXT_LIST)):
            mp3file="%s\\%s.mp3"%(temp_folder,i)
            print(mp3file)
            mp3=None
            with open(mp3file, 'rb') as fi:
                mp3 = fi.read()
            if i in (0,len(TEXT_LIST)-1):
                fo.write(mute_file)
                fo.write(mp3)
                continue
            for jj in range(REPEAT_TIMES):
                fo.write(mp3)
                fo.write(mute_file)
            fo.write(mute_file*WORD_WAIT_SECONDS)
 
    
if __name__ == '__main__':
    check_folders()
    read_words()
    asyncio.run(my_function())
    combine_files()
    print("end")
    
    